'use strict';

angular.module('xuexibangApp')
	.controller('NewestCtrl', function($scope, Exam, Klass, Auth, $state) {
		//console.log("$stateParams", $state.params);
		var examid = $state.params.id;
		var me = Auth.getCurrentUser();
		$scope.examlist = [];
		if (examid) {
			Exam.get({
				id: examid
			}, function(exam) {
				//console.log(exam);
				Klass.get({
					code: exam.klass
				}, function(klass) {
					addExam(klass, exam);
				}, function(err) {
					console.log(err);
				})
			}, function(err) {
				console.log(err);
			})
		} else {
			init();
		}

		function init() {
			var inicode = 0;
			if (Auth.isRole('teacher')) {
				if (me.klasses) {
					inicode = me.klasses[0];
					if (me.chargeklass) {
						inicode = me.chargeklass;
					}
				} else {
					return; //是教师，但没有教授任何班级
				}
			} else {
				if (me.klass) {
					inicode = me.klass;
				} else {
					return; //可能是admin，没有班级
				}
			}

			Klass.get({
				code: inicode
			}, function(klass) {
				Exam.getLastOne({
					code: klass.code
				}, function(exam) {
					addExam(klass, exam);
				}, function(err) {
					console.log(err);
				})
			})

		}

		function addExam(klass, exam) {
			if (exam._id) {
				var examtable = {};
				examtable.title = exam.title;
				examtable.comment = exam.comment;
				examtable.courses = exam.courses;
				examtable.klass = klass;
				examtable.content = [];
				examtable.head = [];
				for (var i = 0; i < exam.courses.length; i++) {
					examtable.head.push('分数');
					examtable.head.push('名次');
				}

				//console.log(exam);
				for (var i = 0; i < exam.content.length; i++) {
					if (Auth.isRole('student') && !(exam.flag && exam.flag == 1) && exam.content[i].student.code != me.code) {
						continue; //学生只能看到自己的成绩
					}
					var examentry = {};
					examentry.student = exam.content[i].student;
					var scorestable = [];
					for (var j = 0; j < exam.content[i].scores.length; j++) {
						scorestable.push(exam.content[i].scores[j].value);
						scorestable.push(exam.content[i].scores[j].rank);
					}
					examentry.scores = scorestable;
					examtable.content.push(examentry);
				}
				//console.log(examtable.content);
				$scope.examlist.push({
					klass: klass,
					exam: examtable
				});
			}
		}
	})
